<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class LoginAuthVerifty extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //校验请求是否传递token
        $this->checkForToken($request);

        try{
            //通过解析token进行身份认证
            if ($user = JWTAuth::parseToken()->authenticate()){
                return $next($request);
            }

            return response()->json([
                'code' => 400,
                'error' => '未登录',
                'LoginURL' => 'http://shopstar.com/api/login'
            ]);
        }catch (TokenExpiredException $exception){
            try{
                //检测到token过期,重新刷新一个token
                $token = $this->auth->refresh();

                $access_token = 'Bearer'.$token;
                //将本次请求的token进行更换
                $request->headers->set('Authorization',$access_token);
                //允许临时进行登录,一个过期的token只能有一次临时登录重新刷新token的机会
                Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
            }catch (JWTException $exception){
                return response()->json([
                   'code' => 400,
                   'error' => '您的身份认证已失效,请重新登录',
                    'LoginURL' => 'http://shopstar.com/api/login'
                ]);
            }
        }
        return $this->setAuthenticationHeader($next($request),$token);
    }
}
